using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ShopPowerTemplate.Entities;
using ShopPowerTemplate.IoC;
using ShopPowerTemplate.Presentation.Mvc.Extensions;
using ShopPowerTemplate.Presentation.Mvc.Models;
using ShopPowerTemplate.Presentation.Mvc.ViewModels;
using ShopPowerTemplate.Services;

namespace ShopPowerTemplate.Presentation.Mvc.Controllers
{
	public partial class OrderStateControllerBase : BaseController
	{
		#region Members

        protected IOrderStateService _orderStateService;
        protected IOrderService _orderService;
        protected ICustomerService _customerService;

        #endregion

        #region Constructors

        public OrderStateControllerBase(IOrderStateService orderStateService, IOrderService orderService, ICustomerService customerService)
        {
            _orderStateService = orderStateService;
            _orderService = orderService;
            _customerService = customerService;
        }	

        #endregion

		#region Index

		// **************************************
        // URL: /OrderState
        // **************************************
		public virtual ActionResult Index()
		{
			IndexOrderStateViewModel viewModel = new IndexOrderStateViewModel();
			ViewBag.PageIndex = this.GetPageIndex();
            ViewBag.PageSize = this.GetPageSize();
			ViewBag.SearchValue = this.GetSearchValue();
		
			return View(viewModel);
		}

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Load(string sidx, string sord, int page, int rows, string search, int mode = 1)
        {
            string searchValue = this.GetSearchValue();
            OrderBy orderBy = this.GetOrderBy();
            int pageIndex = this.GetPageIndex();
            int pageSize = this.GetPageSize();

            if (mode == (int)JQGridActionEnum.DefaultLoad)
            {                
                pageSize = (pageIndex + 1) * pageSize;
                pageIndex = 0;
            }
            else if (mode == (int)JQGridActionEnum.ShowMoreResults)
            {
                pageIndex = page;
                this.SetPageIndex(pageIndex);
            }
            else if (mode == (int)JQGridActionEnum.CustomSearch)
            {
                searchValue = search;
                this.SetSearchValue(searchValue);
                pageIndex = 0;
                this.SetPageIndex(pageIndex);
                orderBy = new OrderBy("", true);
                this.SetOrderBy(orderBy);
            }

            if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                orderBy = new OrderBy(sidx, sord == "asc");
                this.SetOrderBy(orderBy);
            }

            List<OrderState> searchList = _orderStateService.Search(searchValue, orderBy.Property, orderBy.Ascending, pageIndex, pageSize);
            int count = _orderStateService.SearchCount(searchValue);
            
			if (!string.IsNullOrEmpty(sidx)) // Sort request
            {
                pageIndex = this.GetPageIndex();
            }

            var data = new
            {
                total = Math.Ceiling((float)count/(float)pageSize),        // Total pages
                page = pageIndex,      // Current page
                records = count,  // Total records
                rows = from orderState in searchList     // Row data
                       select new
                       {
                           id = orderState.Id,                
                           cell = new string[] {
						   
                                orderState.Name,
								orderState.Description
								
                           }
                       }
            };

            return Json(data);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id)
        {
            try
            {
                _orderStateService.Remove(id);
            }
            catch (RemoveException ex)
            {
                Response.StatusCode = 500;
                return Content(ex.Message);
            }
            return Content(string.Empty);
        }
		
		public virtual FileContentResult Report()
        {
            IList<OrderState> _orderStateList = _orderStateService.Search(this.GetSearchValue());            
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Name;Description");

            // rows
            foreach (OrderState orderState in _orderStateList)
            {
                List<string> rowData = new List<string>() { orderState.Name, orderState.Description };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "OrderState.csv");
        }
		

		#endregion

		#region Create

		// *******************************************
        // URL: /OrderState/Create
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Create()
        {
            OrderState orderState = new OrderState();
            CreateOrderStateViewModel viewModel = Mapper.Map<OrderState, CreateOrderStateViewModel>(orderState);
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Create(CreateOrderStateViewModel orderStateModel)
        {
            if (ModelState.IsValid)
            {
                OrderState orderState = new OrderState();
                AutoMapper.Mapper.Map<CreateOrderStateViewModel, OrderState>(orderStateModel, orderState);
 

				_orderStateService.Add(orderState);

                return RedirectToAction("Edit", new { id = orderState.Id});
            }
            else
            {

                return View(orderStateModel);
            }
		}
		

		#endregion

		#region Edit

		// *******************************************
        // URL: /OrderState/Edit/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Edit(int id)
        {
            OrderState orderState = _orderStateService.Find(id);
            EditOrderStateViewModel viewModel = Mapper.Map<OrderState, EditOrderStateViewModel>(orderState);
            
			return View(viewModel);
        }

		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(EditOrderStateViewModel orderStateModel)
        {
            if (ModelState.IsValid)
            {
                OrderState orderState = _orderStateService.Find(orderStateModel.Id);
                AutoMapper.Mapper.Map<EditOrderStateViewModel, OrderState>(orderStateModel, orderState);
                
				_orderStateService.Change(orderState);

                return RedirectToAction("Index");
            }
            else
            {

                return View(orderStateModel);
            }
		}
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult LoadOrders(string sidx, string sord, int page, int rows, string search, int mode = 1, int masterId = 0)
        {
			OrderState currentOrderState = _orderStateService.Find(masterId);
            List<Order> list = currentOrderState.Orders.ToList();
			int count = list.Count();

			var data = new
            {
                total = 1,        // Total pages
                page = 1,      // Current page
                records = count,  // Total records
                rows = from order in list     // Row data
                       select new
                       {
                           id = order.Id,                
                           cell = new string[] {
                                order.Reference,
								order.Date.ToString(),
								order.ShippingCost.ToString(),
								order.Customer != null ? order.Customer.IdentityDescription : string.Empty
                           }
                       }
            };

            // Return elements
            return Json(data);
        }

		public virtual ActionResult AddOrders(int masterId = 0)
        {
            PopUpOrderViewModel viewModel = new PopUpOrderViewModel();

			List<Customer> allCustomer = _customerService.FindAll();
			viewModel.CustomerList = allCustomer;
			viewModel.OrderStateId = masterId;
			ViewBag.MasterProperty = "OrderState";
            ViewBag.Name = "AddOrders";

            return PartialView("~/Views/Order/PopUp.cshtml", viewModel);
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult AddOrders(PopUpOrderViewModel orderModel)
        {
            if (ModelState.IsValid)
            {
                Order orders = new Order();
                AutoMapper.Mapper.Map<PopUpOrderViewModel, Order>(orderModel, orders);

				OrderState orderState = _orderStateService.Find(orders.OrderState.Id);
				_orderStateService.AddOrders(orderState, orders);
                
				Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Customer> allCustomer = _customerService.FindAll();
				orderModel.CustomerList = allCustomer;
				ViewBag.MasterProperty = "OrderState";
            	ViewBag.Name = "AddOrders";


				return PartialView("~/Views/Order/PopUp.cshtml", orderModel);
            }
        }	
		
		public virtual ActionResult EditOrders(int id, int masterId = 0)
        {
			Order order = _orderService.Find(id);
            PopUpOrderViewModel viewModel = Mapper.Map<Order, PopUpOrderViewModel>(order);

			List<Customer> allCustomer = _customerService.FindAll();
			List<OrderState> allOrderState = _orderStateService.FindAll();
			viewModel.CustomerList = allCustomer;
			viewModel.OrderStateId = masterId;
			ViewBag.MasterProperty = "OrderState";
            ViewBag.Name = "EditOrders";

            return PartialView("~/Views/Order/PopUp.cshtml", viewModel);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult EditOrders(PopUpOrderViewModel orderModel)
        {
            if (ModelState.IsValid)
            {
                Order order = _orderService.Find(orderModel.Id);
                AutoMapper.Mapper.Map<PopUpOrderViewModel, Order>(orderModel, order);

                _orderService.Change(order);

                Response.StatusCode = 200;
                return Content("OK", "text/plain");
            }
            else
            {
				List<Customer> allCustomer = _customerService.FindAll();
				List<OrderState> allOrderState = _orderStateService.FindAll();
				orderModel.CustomerList = allCustomer;
				orderModel.OrderStateList = allOrderState;
				ViewBag.MasterProperty = "OrderState";

                return PartialView("~/Views/Order/PopUp.cshtml", orderModel);
            }
        }
		
		[AcceptVerbs(HttpVerbs.Post)]
        public virtual void DeleteOrders(int id, int masterId = 0)
        {
			Order order = _orderService.Find(id);
			OrderState currentOrderState = _orderStateService.Find(masterId);

            _orderStateService.RemoveOrders(currentOrderState, order);
        }
			
		public virtual FileContentResult ReportOrders(int masterId = 0)
        {
			OrderState currentOrderState = _orderStateService.Find(masterId);
            IList<Order> _ordersList = currentOrderState.Orders.ToList();          
            StringBuilder strBuilder = new StringBuilder();

            // columns
            strBuilder.AppendLine("Reference;Date;ShippingCost;Customer");

            // rows
            foreach (Order order in _ordersList)
            {
                List<string> rowData = new List<string>() { order.Reference, order.Date.ToString(), order.ShippingCost.ToString(), order.Customer != null ? order.Customer.IdentityDescription : string.Empty };
                strBuilder.AppendLine(rowData.Aggregate((x, y) => x + ";" + y));
            }

			// encode report content
            System.IO.MemoryStream content = new System.IO.MemoryStream();
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(content, UTF8Encoding.UTF8))
                writer.Write(strBuilder.ToString());

            return File(content.ToArray(), "text/csv", "Orders.csv");
        }
		

		#endregion

		#region Details

		// *******************************************
        // URL: /OrderState/Details/id
        // *******************************************
		[AcceptVerbs(HttpVerbs.Get)]
        public virtual ActionResult Details(int id)
        {
            OrderState orderState = _orderStateService.Find(id);
            DetailsOrderStateViewModel viewModel = Mapper.Map<OrderState, DetailsOrderStateViewModel>(orderState);
            
			return View(viewModel);
        }
		

		#endregion
	}
}
